import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
    state:{
      count:0,
      userName:'小黑',
      userInfo:[
          {id:1,name:'张益达',sex:1},
          {id:2,name:'林婉茹',sex:0},
      ],
      todos:[
        {id:1,text:'长江一号',done:true},
        {id:2,text:'长江二号',done:false},
        {id:3,text:'长江三号',done:true},
        {id:4,text:'长江四号',done:false},
        {id:5,text:'长江五号',done:true}
      ]
    },
    getters:{        
        doneTodos: state => { //Getter 接受 state 作为其第一个参数      
          return state.todos.filter(todo=>todo.done)  //返回值会根据它的依赖被缓存起来
        },
        doneTodosNo: state => { //Getter 接受 state 作为其第一个参数      
          return state.todos.filter(todo=>!todo.done)  //返回值会根据它的依赖被缓存起来
        },
        doneTodosCount:(state,getters)=>{ //Getter 也可以接受其他 getter 作为第二个参数：
          return getters.doneTodos.length
        },
        userMale:state =>{
            return state.userInfo.filter(item => item.sex)
        },
        userFemale:state =>{
          return state.userInfo.filter(item => !item.sex)
      }
    },
    mutations:{
      increment(state){ //加1
        state.count++
      },
      inreduce(state){  //减1
        state.count--
      },
      inchange(state,num){  //转换
        state.count = num
      },
      userNameChange(state,change){
          state.userName = change
      }
    },
    actions:{//action 可以包含任意异步操作 ,Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象
        getUserInfo:({commit},temp)=>{
            //context.state.userName = token
            setTimeout(() => {
                console.log('1.5秒后出现')
            }, 1500);
            commit('userNameChange',temp.token)
        }
    },
  })
  
  console.log('..............Mutations..................')
  store.commit('increment') //要唤醒一个 mutation handler，你需要以相应的 type 调用 store.commit 方法：
  console.log(store.state.count)  //1
  store.commit('inreduce')
  console.log(store.state.count)  //0
  store.commit('inchange',10)
  console.log(store.state.count)  //10

  console.log(store.state.userName)
  store.commit('userNameChange','小白')
  console.log(store.state.userName)

  export default store